<?php declare(strict_types=1);


namespace App\Rpc\Validator;

use App\Rpc\Model\Dao\UserCaptainDao;
use App\Rpc\Model\Dao\UserCarrierDao;
use App\Rpc\Model\Dao\UserRoleDao;
use App\Rpc\Model\Entity\UserRole;
use Swoft\Validator\Annotation\Mapping\IsInt;
use Swoft\Validator\Annotation\Mapping\IsString;
use Swoft\Validator\Annotation\Mapping\Length;
use Swoft\Validator\Annotation\Mapping\Validator;
use Swoft\Validator\Exception\ValidatorException;
use Swoft\Validator\Contract\ValidatorInterface;
use Swoft\Bean\BeanFactory;
use App\Rpc\Model\Dao\UserDao;
use App\Lib\Error\ErrorConstant;

/**
 * Class UserRoleValidator
 *
 * @since 2.0
 *
 * @Validator(name="UserRoleValidator")
 *
 * @package App\Validator
 */
class UserRoleValidator implements ValidatorInterface
{
    /**
     * @IsString(message="item_id类型不正确")
     * @var string
     */
    protected $item_id;

    /**
     * @IsString(message="用户id类型不正确")
     * @Length(min=32, max=32, message="用户id信息不合法")
     * @var string
     */
    protected $user_id;

    /**
     * @IsString(message="角色id类型不正确")
     * @Length(min=32, max=32, message="角色id信息不合法")
     * @var string
     */
    protected $role_id;

    /**
     * @param array $data
     * @param array $params
     * @return array
     * @throws ValidatorException
     */
    public function validate(array $data, array $params): array
    {
        $op = $params['op'] ?? null;
        $valid_item_id = $data['item_id'] ?? null;

        if (empty($valid_item_id) && $op == 'add') {
            throw new ValidatorException("唯一item_id必须填写", ErrorConstant::VALIDATE_ERROR_CODE);
        }

        if ($op == 'add' && strlen($valid_item_id) != 32) {
            throw new ValidatorException("唯一item_id格式不正确", ErrorConstant::VALIDATE_ERROR_CODE);
        }

        //验证是否存在
        if ($op == 'add' && !($data['user_id']??null)) {
            throw new ValidatorException("请输入用户id", ErrorConstant::VALIDATE_ERROR_CODE);
        }

        //验证是否存在
        if ($op == 'add' && !($data['role_id']??null)) {
            throw new ValidatorException("请输入角色id", ErrorConstant::VALIDATE_ERROR_CODE);
        }

        if($op == 'add'){
            $userRole = BeanFactory::getBean(UserRoleDao::class);
            $info = $userRole->getByWhere(['user_id' => $data['user_id'], 'role_id' => $data['role_id']]);
            if($info){
                throw new ValidatorException('已经存在用户角色关系不能重复添加');
            }
        }

        return $data;
    }
}
